import React, { useState, useEffect } from 'react';

const CheckinCalendar = () => {
  const [checkedDays, setCheckedDays] = useState(new Set());
  const [currentStreak, setCurrentStreak] = useState(0);
  const [totalPoints, setTotalPoints] = useState(0);
  const [todayChecked, setTodayChecked] = useState(false);
  const [showReward, setShowReward] = useState(false);

  // 获取当前月份的天数
  const getCurrentMonthDays = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startDayOfWeek = firstDay.getDay();
    
    return { daysInMonth, startDayOfWeek, year, month };
  };

  const { daysInMonth, startDayOfWeek, year, month } = getCurrentMonthDays();
  const today = new Date().getDate();

  // 初始化数据（从localStorage读取）
  useEffect(() => {
    const savedData = localStorage.getItem('checkin-data');
    if (savedData) {
      const data = JSON.parse(savedData);
      setCheckedDays(new Set(data.checkedDays || []));
      setCurrentStreak(data.currentStreak || 0);
      setTotalPoints(data.totalPoints || 0);
      setTodayChecked(data.checkedDays?.includes(today) || false);
    }
  }, [today]);

  // 保存数据到localStorage
  const saveData = (newCheckedDays, newStreak, newPoints) => {
    const data = {
      checkedDays: Array.from(newCheckedDays),
      currentStreak: newStreak,
      totalPoints: newPoints,
      lastUpdate: new Date().toISOString()
    };
    localStorage.setItem('checkin-data', JSON.stringify(data));
  };

  // 签到逻辑
  const handleCheckin = () => {
    if (todayChecked) return;

    const newCheckedDays = new Set([...checkedDays, today]);
    
    // 计算连续签到天数
    let newStreak = 1;
    for (let i = today - 1; i >= 1; i--) {
      if (newCheckedDays.has(i)) {
        newStreak++;
      } else {
        break;
      }
    }

    // 计算奖励积分
    let pointsEarned = 10; // 基础积分
    if (newStreak >= 7) pointsEarned = 50; // 连续7天
    else if (newStreak >= 3) pointsEarned = 20; // 连续3天

    const newTotalPoints = totalPoints + pointsEarned;

    setCheckedDays(newCheckedDays);
    setCurrentStreak(newStreak);
    setTotalPoints(newTotalPoints);
    setTodayChecked(true);
    setShowReward({ points: pointsEarned, streak: newStreak });

    saveData(newCheckedDays, newStreak, newTotalPoints);

    // 3秒后隐藏奖励提示
    setTimeout(() => setShowReward(false), 3000);
  };

  // 渲染日历
  const renderCalendar = () => {
    const days = [];
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

    // 星期标题
    weekDays.forEach(day => {
      days.push(
        <div key={`week-${day}`} className="calendar-weekday">
          {day}
        </div>
      );
    });

    // 空白天数（月初）
    for (let i = 0; i < startDayOfWeek; i++) {
      days.push(<div key={`empty-${i}`} className="calendar-day empty"></div>);
    }

    // 月份天数
    for (let day = 1; day <= daysInMonth; day++) {
      const isChecked = checkedDays.has(day);
      const isToday = day === today;
      const isPast = day < today;
      const isFuture = day > today;

      days.push(
        <div
          key={day}
          className={`calendar-day ${isChecked ? 'checked' : ''} ${
            isToday ? 'today' : ''
          } ${isPast ? 'past' : ''} ${isFuture ? 'future' : ''}`}
          onClick={isToday && !todayChecked ? handleCheckin : undefined}
        >
          <span className="day-number">{day}</span>
          {isChecked && <div className="check-mark">✓</div>}
          {isToday && !todayChecked && (
            <div className="checkin-hint">点击签到</div>
          )}
        </div>
      );
    }

    return days;
  };

  return (
    <div className="checkin-calendar">
      {/* 统计信息 */}
      <div className="checkin-stats">
        <div className="stat-item">
          <div className="stat-number">{currentStreak}</div>
          <div className="stat-label">连续签到</div>
        </div>
        <div className="stat-item">
          <div className="stat-number">{totalPoints}</div>
          <div className="stat-label">总积分</div>
        </div>
        <div className="stat-item">
          <div className="stat-number">{checkedDays.size}</div>
          <div className="stat-label">本月签到</div>
        </div>
      </div>

      {/* 签到按钮 */}
      <div className="checkin-action">
        <button
          className={`checkin-btn ${todayChecked ? 'checked' : ''}`}
          onClick={handleCheckin}
          disabled={todayChecked}
        >
          {todayChecked ? '今日已签到' : '立即签到'}
        </button>
      </div>

      {/* 日历 */}
      <div className="calendar-grid">
        {renderCalendar()}
      </div>

      {/* 奖励提示 */}
      {showReward && (
        <div className="reward-popup">
          <div className="reward-content">
            <h3>签到成功！</h3>
            <p>获得 {showReward.points} 积分</p>
            {showReward.streak >= 3 && (
              <p className="streak-bonus">
                连续签到 {showReward.streak} 天！
                {showReward.streak >= 7 ? '🎉 超级奖励！' : '🔥 连击奖励！'}
              </p>
            )}
          </div>
        </div>
      )}

      {/* 签到规则 */}
      <div className="checkin-rules">
        <h4>签到规则</h4>
        <ul>
          <li>每日签到获得 10 积分</li>
          <li>连续签到 3 天获得 20 积分</li>
          <li>连续签到 7 天获得 50 积分</li>
          <li>积分可用于兑换奖品</li>
        </ul>
      </div>
    </div>
  );
};

export default CheckinCalendar;